package com.njupt.Tree;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/21 8:47
 * @Description: 637.二叉树的层平均值
 * @Version: 1.0
 */


public class AverageOfLevels {

    public List<Double> averageOfLevels(TreeNode root) {
        ArrayList<Double> results = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        RoundingMode halfUp = RoundingMode.HALF_UP;
        if(root == null) return results;
        queue.addLast(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            Double sum = 0.0;
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.pollFirst();
                sum += treeNode.val;
                if(treeNode.left != null) queue.addLast(treeNode.left);
                if(treeNode.right != null) queue.addLast(treeNode.right);
            }
            BigDecimal bd = BigDecimal.valueOf(sum / size).setScale(5, halfUp);

            results.add(bd.doubleValue());
        }
        return results;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        AverageOfLevels test = new AverageOfLevels();
        List<Double> doubles = test.averageOfLevels(root);
        System.out.println(doubles);
    }
}
